package com.itcast.tanhuaserver.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itcast.tanhua.dubbo.server.api.QuanZiApi;
import com.itcast.tanhua.dubbo.server.api.UsersApi;
import com.itcast.tanhua.dubbo.server.domain.Comment;
import com.itcast.tanhua.dubbo.server.domain.Users;
import com.itcast.tanhua.dubbo.server.vo.PageInfo;
import com.itcast.tanhuaserver.domain.Announcement;
import com.itcast.tanhuaserver.domain.User;
import com.itcast.tanhuaserver.domain.UserInfo;
import com.itcast.tanhuaserver.domain.UserThreadLocal;
import com.itcast.tanhuaserver.service.AnnouncementService;
import com.itcast.tanhuaserver.service.IMService;
import com.itcast.tanhuaserver.service.UserInfoService;
import com.itcast.tanhuaserver.vo.Contacts;
import com.itcast.tanhuaserver.vo.MessageAnnouncement;
import com.itcast.tanhuaserver.vo.MessageLike;
import com.itcast.tanhuaserver.vo.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * @PachageName: com.itcast.tanhuaserver.service.impl
 * @ClassName:
 * @Description: TODO
 * @Author: Hushi
 * @DateTime: 2021/2/2215:11
 * @Version 1.0
 */
@Service
@Slf4j
public class IMServiceImpl implements IMService {

    @Reference(version = "1.0.0")
    private UsersApi usersApi;

    @Value("${tanhua.sso.url}")
    private String url;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private UserInfoService userInfoService;

    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    @Autowired
    private AnnouncementService announcementService;

    /**
     * 添加好友
     *
     * @param userId
     */
    @Override
    public Boolean contactUser(Long userId){
        User user = UserThreadLocal.get();

        Users users = new Users();
        users.setUserId(user.getId().longValue());
        users.setFriendId(userId);

        String returnId = this.usersApi.saveUsers(users);
        if (StringUtils.isNotEmpty(returnId)){
            try {
                String targetUrl = url + "/user/huanxin/contacts/" + user.getId() + "/" + userId;
                ResponseEntity<Void> responseEntity = this.restTemplate.postForEntity(targetUrl, null, Void.class);
                if (responseEntity.getStatusCode().is2xxSuccessful()){
                    return true;
                }
            } catch (RestClientException e){
                //数据库删除好友联系
                this.usersApi.removeUsers(users);
                log.error("注册好友IMService失败~ userId=" + userId,e);
                return false;
            }
        }
        return false;
    }

    @Override
    public PageResult queryContactsList(Integer page, Integer pageSize, String keyword) {
        PageResult pageResult = new PageResult();
        pageResult.setCounts(0);
        pageResult.setPages(0);
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        User user = UserThreadLocal.get();
        List<Users> list = new ArrayList<>();
        if (StringUtils.isNotEmpty(keyword)){
            list = this.usersApi.queryAllUsersList(user.getId().longValue());
        }else{
            PageInfo<Users> usersPageInfo = this.usersApi.queryUsersList(user.getId().longValue(), page, pageSize);
            list = usersPageInfo.getRecords();
        }

        if (CollectionUtils.isEmpty(list)){
            return pageResult;
        }
        List<Long> userIds = new ArrayList<>();
        for (Users users : list) {
            if (!userIds.contains(users.getFriendId())){
                userIds.add(users.getFriendId());
            }
        }

        QueryWrapper<UserInfo> query = new QueryWrapper<>();
        query.in("user_id",userIds);
        if (StringUtils.isNotEmpty(keyword)){
            query.like("nick_name",keyword);
        }
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(query);
        if (CollectionUtils.isEmpty(userInfoList)){
            return pageResult;
        }

        List<Contacts> contactsList = new ArrayList<>();
        if (StringUtils.isNotEmpty(keyword)){
            Contacts contacts = new Contacts();
            for (Users users : list) {
                for (UserInfo userInfo : userInfoList) {
                    if (users.getFriendId().longValue() == userInfo.getUserId().longValue()){
                        contacts.setAvatar(userInfo.getLogo());
                        contacts.setAge(userInfo.getAge());
                        contacts.setNickname(userInfo.getNickName());
                        contacts.setCity(StringUtils.substringBefore(userInfo.getCity(),"-"));
                        contacts.setUserId(userInfo.getUserId().toString());
                        contacts.setGender(userInfo.getSex() == null ? "man" : userInfo.getSex().name().toLowerCase());
                        contactsList.add(contacts);
                    }
                }
            }
        }
        else{
            for (UserInfo userInfo : userInfoList) {
                Contacts contacts = new Contacts();
                contacts.setAvatar(userInfo.getLogo());
                contacts.setAge(userInfo.getAge());
                contacts.setNickname(userInfo.getNickName());
                contacts.setCity(StringUtils.substringBefore(userInfo.getCity(),"-"));
                contacts.setUserId(userInfo.getUserId().toString());
                contacts.setGender(userInfo.getSex() == null ? "man" : userInfo.getSex().name().toLowerCase());
                contactsList.add(contacts);
            }
        }
        pageResult.setItems(contactsList);
        return pageResult;
    }

    @Override
    public PageResult queryMessageLikeList(Integer page, Integer pageSize) {
        return this.messageCommentList(1,page,pageSize);
    }

    @Override
    public PageResult queryMessageCommentList(Integer page, Integer pageSize) {
        return this.messageCommentList(2,page,pageSize);
    }

    @Override
    public PageResult queryMessageLoveList(Integer page, Integer pageSize) {
        return this.messageCommentList(3,page,pageSize);
    }

    @Override
    public PageResult queryMessageAnnouncementList(Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setCounts(0);
        pageResult.setPages(0);
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        IPage<Announcement> announcementIPage = this.announcementService.queryList(page, pageSize);
        List<Announcement> records = announcementIPage.getRecords();
        if (CollectionUtils.isEmpty(records)){
            return pageResult;
        }

        List<MessageAnnouncement> messageAnnouncements = new ArrayList<>();
        for (Announcement record : records) {
            MessageAnnouncement messageAnnouncement = new MessageAnnouncement();
            messageAnnouncement.setId(record.getId().toString());
            messageAnnouncement.setTitle(record.getTitle());
            messageAnnouncement.setDescription(record.getDescription());
            messageAnnouncement.setCreateDate(new DateTime(record.getCreated()).toString("yyyy-MM-dd HH:mm:ss"));

            messageAnnouncements.add(messageAnnouncement);
        }
        pageResult.setItems(messageAnnouncements);
        return pageResult;
    }

    public PageResult messageCommentList(Integer type,Integer page, Integer pageSize){
        PageResult pageResult = new PageResult();
        pageResult.setCounts(0);
        pageResult.setCounts(0);
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        User user = UserThreadLocal.get();
        PageInfo<Comment> pageInfo = this.quanZiApi.queryCommentListByUser(user.getId().longValue(),type, page, pageSize);
        List<Comment> records = pageInfo.getRecords();
        if (CollectionUtils.isEmpty(records)){
            return  pageResult;
        }

        List<Long> userIds = new ArrayList<>();
        for (Comment record : records) {
            if (!userIds.contains(record.getUserId())){
                userIds.add(record.getUserId());
            }
        }

        QueryWrapper<UserInfo> query =  new QueryWrapper<>();
        query.in("user_id",userIds);
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(query);

        List<MessageLike> messageLikes = new ArrayList<>();
        for (Comment record : records) {
            for (UserInfo userInfo : userInfoList) {
                if (record.getUserId().longValue() == userInfo.getUserId().longValue()){
                    MessageLike messageLike = new MessageLike();
                    messageLike.setAvatar(userInfo.getLogo());
                    messageLike.setNickname(userInfo.getNickName());
                    messageLike.setId(record.getId().toHexString());
                    messageLike.setCreateDate(new DateTime(record.getCreated()).toString("yyyy-MM-dd HH:mm:ss"));
                    messageLikes.add(messageLike);
                    break;
                }
            }
        }
        pageResult.setItems(messageLikes);
        return pageResult;
    }
}
